package com.user.command;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.user.applaction.SessionManager;
import com.user.mapping.UserMapping;
import com.user.tool.Tool;

public class DeleteCommand implements Command {

	@Override
	public void excute() {
		SqlSession session = SessionManager.getInstance().getSession();
		UserMapping mapper = session.getMapper(UserMapping.class);
		long begin =  System.currentTimeMillis();
		Tool.printMsg("正在载入所有用户信息... ");
		List<Integer> idList = mapper.selectAllId();
		long end =  System.currentTimeMillis();
		long res = end - begin;
		Tool.printMsg("载入完成," + res + "毫秒");
		Iterator<Integer> it = idList.iterator();
		// 得到ID次数
		int count = 0;
		int id = 0;
		// 判断输入
		while (true) {
			try {
				id = Integer.valueOf(Tool.askUserInputNotNull("输入您要删除用户的ID，输入0或1以退出当前操作"));
			} catch (Exception e) {
				Tool.printMsg("输入的不是数字");
				continue;
			}
			// 如果输入0直接退出命令
			if (0 == id || 1 == id) {
				Tool.printMsg("操作取消");
				return;
			}
			// 遍历ID出现次数
			while (it.hasNext()) {
				if (id == it.next()) {
					count++;
				}
			}
			// 判断是否存在
			if (!(count > 0)) {
				Tool.printMsg("输入的ID不存在，重新输入");
				continue;
			} else if (count > 0) {
				mapper.deleteById(id);
				String yesOrNo = "";
				// 确认是否删除
				while (true) {
					yesOrNo = Tool.askUserInputNotNull("您确定要删除ID为" + id + "的用户？(YES or NO)");
					if (!("YES".equals(yesOrNo.toUpperCase()) || "NO".equals(yesOrNo.toUpperCase()))) {
						Tool.printMsg("错误命令,重新输入");
						continue;
					} else if ("YES".equals(yesOrNo.toUpperCase())) {
						Tool.printMsg("删除成功");
						session.commit();
						session.close();
						return;
					} else if ("NO".equals(yesOrNo.toUpperCase())) {
						Tool.printMsg("已取消");
					}
				}

			}
		}

	}

}
